const { parse } = require('es-module-lexer');
const { readBody, resolveRelativePath } = require("../../utils");
const MagicString = require('magic-string');
const { clientPublicPath } = require('./serverPluginClient');
const { srcImportMap } = require('./serverPluginVue');

function rewriteImports(source, ctx) {
  let ms = new MagicString(source);
  let imports = parse(source);
  for (let i = 0; i < imports[0].length; i++) {
    const { s, e } = imports[0][i];
    const id = source.slice(s, e);
    if (/^[^\.\/]/.test(id)) {
      let result = `/@modules/${id}`;
      ms.overwrite(s, e, result);
    } else {
      if(ctx.query.t && id.endsWith('.js')) {
        let currentFilePath = ctx.url.toString().split('?')[0];
        let srcImportKey = resolveRelativePath(id, currentFilePath);
        let path = srcImportMap.get(srcImportKey);
        if(path === currentFilePath) {
          let result = `${id}?t=${ctx.query.t}`;
          ms.overwrite(s, e, result);
        }
      }
    }
  }
  return ms.toString();
}

function moduleRewritePlugin(context) {
  const { app, root } = context;


  app.use(async (ctx, next) => {
    await next();

    if (ctx.body && ctx.response.is('js') && ctx.path !== clientPublicPath) {
      // 只处理js文件

      const source = await readBody(ctx.body);

      const result = rewriteImports(source, ctx);

      ctx.type = 'js';

      ctx.body = result;
    }
  })
}

module.exports = moduleRewritePlugin;